<template>
  <div>
    <el-dialog
        :visible.sync="uploadDialog"
        :title="title"
        @close="close"
        width="53%"
        center
        top="100px"
    >
      <slot name="form"></slot>
      <span style="color: #ce0e0f">*</span>
      <span>上传导入文件</span>
      <el-upload
          v-if="uploadDialog"
          class="upload-demo"
          :headers="headers"
          :action="`${$apiHost}/common/fileImgUrl`"
          :on-change="handleFileChange"
          :on-success="onSuccess"
          :on-error="onError"
          :before-upload="onBefore"
          :on-remove="onRemove"
          :limit="1"
          :on-exceed="onExceed"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传excel文件，且不超过500kb
        </div>
      </el-upload>
      <slot name="table"></slot>
      <slot name="btn"></slot>
    </el-dialog>
  </div>
</template>

<script>
import store from "../../../store";

export default {
  name: "uploadExceal",
  data() {
    return {
      token: store.state.tokenv3,
      uploadDialog: false,
      selectedFile: null,
    };
  },
  props: {
    title: {
      type: String,
      default: '导入表格'
    }
  },
  computed: {
    headers() {
      const token = this.token || this.$quinn.getStorage("token");
      return {
        token,
      };
    },
  },
  created() {
  },

  methods: {
    onExceed() {
      this.$message("文件上传已上线！");
    },
    close() {
      this.$emit("close");
    },
    onRemove() {
      this.$emit("removeStatus");
    },
    addDialogClose() {
      this.uploadDialog = false
    },
    handleFileChange(file) {
      console.log(file.raw, ".........");
      this.selectedFile = file.raw
    },
    openDialog(val) {
      this.uploadDialog = true;
    },
    onSuccess(res, file) {
      // this.selectedFile=file
      if (res.code != 200) {
        this.$message(res.msg);
      } else {
        this.$message({message: "导入成功！", type: "success"});
        console.log(res)
        this.$emit("addStatus", res.result[0], this.selectedFile);
      }

        this.loading = false;
    },
    onError(e) {
      this.uploadDialog = false;
      this.$message("导入失败");
    },
    onBefore(file) {
      console.log(file)
      // 进行文件类型和大小检查
      const isExcel =
          file.type === "application/vnd.ms-excel" ||
          file.type ===
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      if (!isExcel) {
        this.$message.error("只能上传Excel文件");
        return false; // 返回 false，阻止上传
      }
      // const isLt500KB = file.size / 1024 < 500;
      // if (!isLt500KB) {
      //   this.$message.error("文件大小不能超过500KB");
      //   return false; // 返回 false，阻止上传
      // }

      // 如果所有检查都通过，则允许上传
      return true;
    },
  },
};
</script>

<style scoped></style>
